package com.dyz.leetcode;

public class RemoveNthFromEnd19 {
    public static void main(String[] args) {
        ListNode d1 = new ListNode(1);
        ListNode d2 = new ListNode(2);
        ListNode d3 = new ListNode(3);
        ListNode d4 = new ListNode(4);
        ListNode d5 = new ListNode(5);
        ListNode tmp = d1;
        tmp.next = d2;
        tmp = tmp.next;
        tmp.next = d3;
        tmp = tmp.next;
        tmp.next = d4;
        tmp = tmp.next;
        tmp.next = d5;
        ListNode listNode = new RemoveNthFromEnd19().removeNthFromEnd(d1, 2);
        while (listNode!=null){
            System.out.println(listNode.val);
            listNode = listNode.next;
        }

    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(n<=0 || head==null){return head;}
        if(n==1){return head.next;}

        ListNode body = head;
        ListNode cur = body.next;
        int index = 2;
        while (index <= n && cur!=null){
            if(index==n){
                body.next = cur.next;
                break;
            }
            body = cur;
            cur = cur.next;
            index++;
        }
        return head;
    }

    public ListNode removeNthFromEnd1(ListNode head, int n) {
        if(n<=0 || head==null){return head;}
        //求节点个数
        ListNode tmp = head;
        int index = 0;
        while (tmp!=null){
            index ++;
            tmp = tmp.next;
        }
        if(index<n){
            return head;
        }
        int k = index-n+1;
        if(k==1){return head.next;}

        ListNode body = head;
        ListNode cur = body.next;
        int p = 2;
        while (p <= k && cur!=null){
            if(p==k){
                body.next = cur.next;
                break;
            }
            body = cur;
            cur = cur.next;
            p++;
        }
        return head;

    }
}
